package clone方法的讲解;

import lombok.Builder;

import java.io.*;

@Builder
public class DeepClone {


    public<T> T  deepClone(T deepClone) throws IOException, ClassNotFoundException {
        //创建ByteArrayOutputStream对象，用来将数据转成字节
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        //创建ObjectOutputStream对象，用来关联ByteArrayOutputStream
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        //使用ObjectOutputStream的writeObject方法，读取要复制的对象
        oos.writeObject(deepClone);
        //使用ByteArrayInputStream读取ByteArrayOutputStream中的字节
        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        //创建ObjectInputStream读取对象字节数据，进行创建新的对象
        ObjectInputStream ois = new ObjectInputStream(bis);
        return (T) ois.readObject();
    }
}
